package fun.tan90.easy.binlog.manager.service.impl;

import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import fun.tan90.easy.binlog.base.convention.enums.IErrorCode;
import fun.tan90.easy.binlog.base.convention.exception.ClientException;
import fun.tan90.easy.binlog.manager.property.EasyBinlogManagerProperties;
import fun.tan90.easy.binlog.manager.service.SysCaptchaService;
import fun.tan90.easy.binlog.manager.model.cmd.SysUserLoginCmd;
import fun.tan90.easy.binlog.manager.model.vo.SysUserInfoVo;
import fun.tan90.easy.binlog.manager.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * description TODO
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2023/6/12 22:00
 */
@Slf4j
@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    EasyBinlogManagerProperties easyBinlogManagerProperties;

    @Resource
    SysCaptchaService sysCaptchaService;

    @Override
    public String basicAuth(SysUserLoginCmd sysUserLoginCmd) {
        sysCaptchaService.validate(sysUserLoginCmd.getCaptchaKey(), sysUserLoginCmd.getCaptchaValue());
        String username = sysUserLoginCmd.getUsername();
        String password = sysUserLoginCmd.getPassword();
        if (!easyBinlogManagerProperties.getUsername().equals(username) || !easyBinlogManagerProperties.getPassword().equals(password)) {
            throw new ClientException(IErrorCode.AUTH_1001001);
        }
        boolean rememberMe = sysUserLoginCmd.isRememberMe();
        SaLoginModel saLoginModel = new SaLoginModel();
        if (rememberMe) {
            long rememberMeDays = sysUserLoginCmd.getRememberMeDays();
            saLoginModel.setTimeout(rememberMeDays * 24 * 3600);
        }
        StpUtil.login("1", saLoginModel.setIsLastingCookie(rememberMe));
        String tokenValue = StpUtil.getTokenValue();

        SysUserInfoVo sysUserInfoVo = SysUserInfoVo.builder()
                .userId("1")
                .userName("管理员")
                .roles(StpUtil.getRoleList())
                .permissions(StpUtil.getPermissionList())
                .build();
        StpUtil.getSession().set("sysUserInfo", sysUserInfoVo);
        return tokenValue;
    }

    @Override
    public SysUserInfoVo userInfo() {
        return StpUtil.getSession().getModel("sysUserInfo", SysUserInfoVo.class);
    }
}
